<script setup lang="ts">
import { request } from '@/apis';
import { closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant';
import { onMounted, ref } from 'vue';
import base64ToBlob from 'b64-to-blob'

// 5. 获取用户有信息数据
const profile = ref<ProfileInfo>({} as ProfileInfo)
// onMounted可以在页面使用多个，就是谁在前面，谁的代码先执行
onMounted(async()=>{
  // 调接口
  showLoadingToast({message:'正在加载....', duration:0, forbidClick: true})
  // 发请求拿数据
  const res = await request.get<MkResponse<ProfileInfo>>('member/profile')
  closeToast()
  // 赋值
  profile.value = res.data.result
  console.log(profile.value);
  // 渲染页面
  // 处理日期
  birthday.value = profile.value.birthday.split('-')
})

// 头像处理 -
// showAvatar控制修改头像弹层的显示/隐藏
const showAvatar = ref(false)
const avatarActions =  [
      { name: '相册' },
      { name: '拍照' }
    ];

  // 打开相册/相机
const onSelectAvatar = async (action: ActionSheetAction, index: number)=>{
  // console.log(action,index);
  // 隐藏动作面板
  showAvatar.value =false
  if (index === 0) {
    // 相册上传
    const data = await mk.pickerPhoto()
    onUpdateAvatar(data)
  }else if (index === 1){ 
    // 拍照上传
    const data = await mk.pickerCamera()
    onUpdateAvatar(data)
  }
}
const onUpdateAvatar = async (str: string) => {
  // 1. 把base64编码转成图片文件对象
  // const image = base64ToBlob(str,'image/jpeg')
  // console.log(image);
  try {
    showAvatar.value = false
    showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    const image = base64ToBlob(str, 'image/jpeg')
    // 2. 包装formData对象
    const fd = new FormData()
    // append 往对象里面添加键值，图片对象添加进FormData
    fd.append('file', image, Date.now() + '.jpeg')
    // 3. 调接口
    const res = await request.post<MkResponse<{ avatar: string }>>('member/profile/avatar', fd)
    closeToast
    profile.value.avatar = res.data.result.avatar

    // 4. 修改原生侧的头像
    const user =await mk.queryUser()
    user.avatar = res.data.result.avatar
    await mk.updateUser(user)
    showToast({ message: '上传成功' })
  } catch (err) {
    showToast({ message: '上传失败' })
  }
}

// 2.选择出生日期
const showBirthdayPopup = ref(false)
const currentDate = new Date()
const birthday = ref([
  String(currentDate.getFullYear()),
  String(currentDate.getMonth()+1),
  String(currentDate.getDate())
])
const selectBirthDay = (data:{selectedValues: string[]}) => {
  console.log(data.selectedValues);
  showBirthdayPopup.value = false
  birthday.value = data.selectedValues
  profile.value.birthday = data.selectedValues.join('-')
}

// 3. 选择地址
const showLocationPopup = ref(false)
const areaColumns = ref<AreaColumns>({}as AreaColumns)
// 组件加载完毕执行
onMounted(async ()=>{
  try {
    areaColumns.value = await mk.getAreaColumns()
    // console.log(res);
    
  } catch (error) {
    showToast('sdk异常')
  }
})
const onSelectLocation = () => {
  showLocationPopup.value = false
}

// 4. 选择职业
const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' }
]
const showProfessionPopup = ref(false)
const onSelectProfession = () => {
  showProfessionPopup.value = false
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头部区域 -->
     <div class="avatar">
      <van-image @click="showAvatar = true" width="100" height="100" round class="avatar-img"  :src="profile.avatar">
      </van-image>
        <!-- 修改头像 -->
      <div  class="avatar-btn" @click="showAvatar = true">
        <div>修改头像</div>
      </div>
      <!-- 头像动作面板 
       通过v-model:show="showAvatar"控制面板的显示与隐藏
       通过action控制面板的选项 
       通过@select点里面的选项触发的事件  -->
       <van-action-sheet v-model:show="showAvatar" :actions="avatarActions" @select="onSelectAvatar" cancel-text="取消" style="padding-bottom: 30px"/>
     </div>

     <!-- 表单区域 -->
      <van-cell-group>
        <van-field v-model="profile.account" label="账号" readonly  />
        <van-field v-model="profile.nickname" label="昵称" placeholder="请输入昵称" />
        <van-cell title="性别" class="gender">
        <van-radio-group v-model="profile.gender" direction="horizontal">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
        </van-cell>
        <van-field v-model="profile.birthday" label="生日" placeholder="请选择日期" readonly @click="showBirthdayPopup = true"/>
        <!-- 这里是选择生日弹层 -->
         <van-popup v-model:show="showBirthdayPopup" position="bottom">
          <van-date-picker v-model="birthday" title="选择日期" :min-date="new Date(1960, 0, 1)" @cancel="showBirthdayPopup = false" @confirm="selectBirthDay "/>
         </van-popup>
        <van-field v-model="profile.fullLocation" label="所在地" placeholder="请选择所在地" readonly @click="showLocationPopup = true"/>
        <!-- 选择地址弹层 -->
         <van-popup v-model:show="showLocationPopup" position="bottom">
          <van-area title="选择所在地" :area-list="areaColumns" 
          @cancel="showLocationPopup = false" 
          @confirm="onSelectLocation"
          />
          
         </van-popup>
        <van-field v-model="profile.profession" label="职业" placeholder="请选择职业" readonly @click="showProfessionPopup = true"/>
        <!-- 选择职业弹层 -->

        <van-popup v-model:show="showProfessionPopup" position="bottom">
          <van-picker
            title="职业"
            
            :columns="columns" 
            @confirm="onSelectProfession"
            @cancel="showProfessionPopup = false"
          />
         </van-popup>
      </van-cell-group>

      <!-- 提交按钮 -->
       <div class="submit" >
         <!-- block宽占满  -->
        <!-- round变圆角 -->
        <van-button block round type="primary" >保存资料</van-button>
       </div>
       


  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
